package com.drawing.controller;

import static com.drawing.common.GsonUtils.toJSON;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;

import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.drawing.common.CommonData;
import com.drawing.pojo.ImageInfo;
import com.drawing.pojo.param.ImageParam;
import com.drawing.service.IImageService;

/**
 * @author zhaozhenhang <zhaozhenhang@kuaishou.com>
 * Created on 2023-10-10
 */
@RestController
@RequestMapping("/image")
public class ImageController {

    private static final Logger logger = LoggerFactory.getLogger(ImageController.class);

    @Autowired
    private IImageService iImageService;

    @PostMapping("/saveImage")
    public CommonData saveImage(@RequestParam("file") MultipartFile file, String fileName, String type) {
        if (file.isEmpty()) {
            return CommonData.success("file is empty");
        }
        try {
            ImageInfo info = iImageService.saveImage(file, fileName, type);
            if (isBlank(info.getFileUrl())) {
                return CommonData.error("文件上传路径为null");
            }
            return CommonData.success("SUCCESS", toJSON(info));
        } catch (Throwable e) {
            logger.error("【path】/insert_qi_niu: ", e);
            return CommonData.error();
        }
    }

    @GetMapping("/queryImage")
    public CommonData queryImage(ImageParam param) {
        try {
            List<ImageInfo> pictures = iImageService.queryImage(param);
            return CommonData.success(pictures.stream().findFirst());
        } catch (Exception e) {
            logger.error("queryImage error: ", e);
            return CommonData.error(null);
        }
    }
}

